package com.zhao.blog.controller.admin;

import com.zhao.blog.pojo.Type;
import com.zhao.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.jws.WebParam;

/**
 * @author xiaoZhao
 * @date 2021/12/29
 * @describe
 */
@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService service;

    //跳转至分类页
    @GetMapping("/types")
    public String types(@PageableDefault(size = 5, sort = {"id"}, direction = Sort.Direction.ASC)
                                Pageable pageable, Model model) {

        model.addAttribute("page", service.listTypes(pageable));
        return "admin/types";
    }

    //跳转新增分类页
    @GetMapping("/types/toAddType")
    public String toAddType(Model model) {
        model.addAttribute("type", new Type());
        return "admin/addTypes";
    }

    @GetMapping("/types/{id}/editType")
    public String toeditType(@PathVariable Long id, Model model){
        model.addAttribute("type",service.getType(id));
        return "admin/addTypes";
    }

    //添加分类
    @PostMapping("/addTypes")
    public String addType(Type type, RedirectAttributes attributes ) {
        Type t = service.saveType(type);
        if (t == null) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return "redirect:/admin/types";
    }

    //更新
    @PostMapping("/editType/{id}")
    public String editType(Type type, RedirectAttributes attributes,@PathVariable Long id) {
        Type t = service.updateType(id,type);
        if (t == null) {
            attributes.addFlashAttribute("message", "更新失败");
        } else {
            attributes.addFlashAttribute("message", "更新成功");
        }
        return "redirect:/admin/types";
    }

    //删除
    @GetMapping("/types/{id}/delete")
    public String deleteType(@PathVariable Long id ,RedirectAttributes attributes){
        service.deleteType(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/types";
    }
}


